package graphic;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.LinkedList;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import core.Server;

public class MainFrame extends JFrame {

	protected static MainFrame MAINFRAME;
	
	JPanel centerPanel;

	public MainFrame()
	{
		super("Server");
		
		System.out.println("COSTRUTTORE MAINFRAME SERVER");
		
		this.centerPanel = new JPanel(new BorderLayout());
	
		JPanel releasePanel = new JPanel(new BorderLayout());
		releasePanel.add(ReleasesListPanel.getIstance(), BorderLayout.CENTER);
		releasePanel.add(ReleaseNotePanel.getIstance(), BorderLayout.SOUTH);

		System.out.println("STEP 1");
		
		this.centerPanel.add(ToolBar.getInstance(), BorderLayout.NORTH);
		this.centerPanel.add(UsersPanel.getInstance(), BorderLayout.WEST);
		this.centerPanel.add(FilesTabbedPanel.getInstance(), BorderLayout.CENTER);
		this.centerPanel.add(releasePanel, BorderLayout.EAST);
		this.centerPanel.add(LogPanel.getInstance(), BorderLayout.SOUTH);

		System.out.println("STEP 2");
		
		super.getContentPane().add(this.centerPanel);
		
		System.out.println("STEP 3");
		
		super.setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		System.out.println("STEP 4");
		
		super.pack();
		
		System.out.println("STEP 5");

		//super.validate();
		
		System.out.println("STEP 6");
		
		super.setVisible(true);

		System.out.println("INTERFRACCIA AVVIATA");
	}

	public void startServer()
	{
		ToolBar.getInstance().disableAllButtonsInsteadOf(new LinkedList<String>());
		ToolBar.getInstance().enableAllButtonsInsteadOf(ToolBar.ONLY_RUN);
		FilesTabbedPanel.getInstance().refreshPanel();
		
		super.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		super.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e){
				MainFrame.getInstance().close();				
			}
		});
	
		LogPanel.getInstance().setPreferredSize(new Dimension((int) super.getSize().getWidth(), 100));
		
		super.pack();
	}
	
	public void stopServer()
	{	
		ToolBar.getInstance().disableAllButtonsInsteadOf(ToolBar.ONLY_RUN);
	}
	
	public void showMessage(String message, int type)
	{
	    JOptionPane optionPane = new JOptionPane(message, type);
	    JDialog dialog = optionPane.createDialog(this, message);
	    dialog.pack();
	    
		Dimension dim = super.getSize();
		int x = (dim.width - dialog.getSize().width) / 2;
		int y = (dim.height - dialog.getSize().height) / 2;
	    
	    dialog.setLocation(x, y);
	    dialog.setVisible(true);
	}
	
	public void close()
	{
		try {
			Server.getInstance().stopServer();
		} catch (IOException e) {}
		
		super.dispose();
	}
	
	public static synchronized MainFrame getInstance()
	{
		if(MAINFRAME == null) MAINFRAME = new MainFrame();
		return MAINFRAME;
	}
}
